<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\order;


use app\common\model\callback\OrderCallback;
use app\common\model\click\CpaClick;
use app\common\model\click\UserCallback;
use app\common\model\media\Media;
use app\common\model\order\Order;
use app\common\logic\BaseLogic;
use app\common\model\user\User;
use app\lib\MessageBus\EventType;
use app\common\service\media\MediaService;
use think\facade\Db;
use think\facade\Log;


/**
 * Order逻辑
 * Class OrderLogic
 * @package app\adminapi\logic
 */
class OrderCallbackLogic extends BaseLogic
{
    /**
     * @notes 订单回传
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/01 10:45
     */
    public static function orderReturn($params): bool
    {
        $order_id      = $params['order_id'];
        $orderCallback = OrderCallback::where('order_id', $order_id)->findOrEmpty();
        if (!$orderCallback->isEmpty()) {
            if ($orderCallback->return_status == 1) {
                self::setError('订单已回传');
                return false;
            }
            $userCallback                 = UserCallback::where('user_id', $orderCallback->user_id)->findOrEmpty();
            $user                         = User::where('id', $orderCallback->user_id)->findOrEmpty();
            $message['promotion_link_id'] = $user->promotion_link_id;
            $message['user_id']           = $orderCallback->user_id;
            $message['order_id']          = $order_id;
            $order                        = Order::where('id', $order_id)->findOrEmpty();
            switch ($user->source) {
                case Media::SOURCE_JL :
                    $callback_param = MediaService::getJlCallbackParam($userCallback, $user->promotion_link_id);
                    if ($callback_param) {
                        $orderCallback->match_status = 1;
                        $click                       = CpaClick::where('callback_param', $callback_param)->findOrEmpty();
                        $orderCallback->ad_name      = $click->promotion_name ?? '';
                        $orderCallback->project_id   = $click->project_id ?? '';
                        $orderCallback->project_name = $click->project_name ?? '';
                        $money                       = $order['money'] * 100;
                        $result                      = MediaService::JlReturn($message, $callback_param, MediaService::JL_TYPE_PAYMENT, $money);
                        if ($result['code'] == 0) {
                            // 回传成功
                            self::saveOrderReturn($orderCallback, $userCallback);
                            return true;
                        } else {
                            self::setError('补充回传失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_UC :
                    $callbackUrl = MediaService::getUcCallback($userCallback, $user->promotion_link_id);
                    if ($callbackUrl) {
                        $orderCallback->match_status = 1;
                        $payResult                   = MediaService::UcReturn($message, $callbackUrl, MediaService::UC_TYPE_PAY);
                        $paymentResult               = MediaService::UcReturn($message, $callbackUrl, MediaService::UC_TYPE_PAYMENT);
                        if ($payResult && $paymentResult) {
                            // 回传成功
                            self::saveOrderReturn($orderCallback, $userCallback);
                            return true;
                        } else {
                            self::setError('补充回传失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_KS :
                    $ksCallback = MediaService::getKsCallback($userCallback, $user->promotion_link_id);
                    if ($ksCallback) {
                        $orderCallback->match_status = 1;
                        $money                       = $order['money'];
                        $result                      = MediaService::KsReturn($message, $ksCallback, MediaService::KS_TYPE_PAYMENT, $money);
                        if ($result) {
                            // 回传成功
                            self::saveOrderReturn($orderCallback, $userCallback);
                            return true;
                        } else {
                            self::setError('补充回传失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_BD :
                    list($type, $callbackUrl) = MediaService::getBdCallback($userCallback, $user->promotion_link_id);
                    if ($type && $callbackUrl) {
                        $orderCallback->match_status = 1;
                        $money                       = $order['money'];
                        $result                      = MediaService::BdReturn($message, $type, $callbackUrl, MediaService::BD_TYPE_PAYMENT, $money);
                        if ($result) {
                            // 回传成功
                            self::saveOrderReturn($orderCallback, $userCallback);
                            return true;
                        } else {
                            self::setError('补充回传失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_VIVO :
                    $click = MediaService::getVivoClick($userCallback, $user->promotion_link_id);
                    if (!$click->isEmpty()) {
                        $orderCallback->match_status = 1;
                        $money                       = $order['money'];
                        $result                      = MediaService::VivoReturn($message, $click, MediaService::VIVO_TYPE_PAYMENT, $money);
                        if ($result) {
                            // 回传成功
                            self::saveOrderReturn($orderCallback, $userCallback);
                            return true;
                        } else {
                            self::setError('补充回传失败');
                            return false;
                        }
                    }
                    break;
            }
            self::setError('补充回传失败-未匹配到监测链接');
            return false;
        }
        self::setError('订单不存在');
        return false;
    }

    public static function saveOrderReturn($orderCallback, $userCallback)
    {
        if ($userCallback->is_report == 0) {
            $userCallback->is_report = 1;
            $userCallback->save();
        }
        $orderCallback->return_status  = 1;
        $orderCallback->reporting_time = time();
        $orderCallback->save();
        return true;

    }

    /**
     * @notes 上报付费
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/01 10:45
     */
    public static function reportPay($params): bool
    {
        $message['user_id'] = $params['id'];
        $userCallback       = UserCallback::where('user_id', $message['user_id'])->findOrEmpty();
        if (!$userCallback->isEmpty()) {
            if ($userCallback->is_report == 1) {
                self::setError('用户已上报');
                return false;
            }
            $user  = User::where('id', $message['user_id'])->findOrEmpty();
            $money = 58;
            switch ($user->source) {
                case Media::SOURCE_JL :
                    $callback_param = MediaService::getJlCallbackParam($userCallback, $user->promotion_link_id);
                    if ($callback_param) {
                        $result = MediaService::JlReturn($message, $callback_param, MediaService::JL_TYPE_PAYMENT, $money);
                        if ($result['code'] == 0) {
                            $userCallback->is_report = 1;
                            $userCallback->save();
                            // 回传成功
                            return true;
                        } else {
                            self::setError('上报失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_UC :
                    $callbackUrl = MediaService::getUcCallback($userCallback, $user->promotion_link_id);
                    if ($callbackUrl) {
                        $result = MediaService::UcReturn($message, $callbackUrl, MediaService::UC_TYPE_PAYMENT);
                        if ($result) {
                            // 回传成功
                            $userCallback->is_report = 1;
                            $userCallback->save();
                            return true;
                        } else {
                            self::setError('上报失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_KS :
                    $ksCallback = MediaService::getKsCallback($userCallback, $user->promotion_link_id);
                    if ($ksCallback) {
                        $result = MediaService::KsReturn($message, $ksCallback, MediaService::KS_TYPE_PAYMENT, $money);
                        if ($result) {
                            $userCallback->is_report = 1;
                            $userCallback->save();
                            return true;
                        } else {
                            self::setError('上报失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_BD :
                    list($type, $callbackUrl) = MediaService::getBdCallback($userCallback, $user->promotion_link_id);
                    if ($type && $callbackUrl) {
                        $result = MediaService::BdReturn($message, $type, $callbackUrl, MediaService::BD_TYPE_PAYMENT, $money);
                        if ($result) {
                            // 回传成功
                            $userCallback->is_report = 1;
                            $userCallback->save();
                            return true;
                        } else {
                            self::setError('上报失败');
                            return false;
                        }
                    }
                    break;
                case Media::SOURCE_VIVO :
                    $click = MediaService::getVivoClick($userCallback, $user->promotion_link_id);
                    if (!$click->isEmpty()) {
                        $result = MediaService::VivoReturn($message, $click, MediaService::VIVO_TYPE_PAYMENT, $money);
                        if ($result) {
                            // 回传成功
                            $userCallback->is_report = 1;
                            $userCallback->save();
                            return true;
                        } else {
                            self::setError('上报失败');
                            return false;
                        }
                    }
                    break;
            }
            self::setError('平台用户不可上报');
            return false;
        }
        self::setError('上报失败');
        return false;
    }
}
